/**
 * 日历待办
 * 任务管理模块
 * 负责管理待办事项的添加、查看和更新
 */

const { ipcRenderer } = require('electron');
const { handleError, ErrorTypes, tryCatch } = require('../../common/error-handler');
const { showToast } = require('../../common/show-toast');
// 模块状态
let isInitialized = false;
let calendar = null;
let tasks = JSON.parse(localStorage.getItem('calendarTasks') || '[]');
let currentView = 'dayGridMonth';

/**
 * 当前日历视图状态
 */
const CalendarViewType = {
    MONTH: 'month',
    WEEK: 'week',
    DAY: 'day',
    SCHEDULE: 'schedule'
};

let currentDate = new Date();
const taskEditModal = document.getElementById('task-edit-modal');
const taskForm = document.getElementById('task-form');
const taskModalTitle = document.getElementById('task-modal-title');
// const taskTitle = document.getElementById('task-title');
// const taskDescription = document.getElementById('task-description');
const taskDate = document.getElementById('task-date');
const taskStartTime = document.getElementById('task-start-time');
const taskEndTime = document.getElementById('task-end-time');
const taskColor = document.getElementById('task-color');
const taskCompleted = document.getElementById('task-completed');
const taskNotification = document.getElementById('task-notification');
// const taskSaveBtn = document.getElementById('task-save-btn');
const taskDeleteBtn = document.getElementById('task-delete-btn');
const taskCancelBtn = document.getElementById('task-cancel-btn');

// 任务通知定时器
let taskNotificationInterval = null;
// 已通知任务ID集合，防止重复通知
const notifiedTaskIds = new Set();

// 日历视图切换按钮
const monthViewBtn = document.getElementById('month-view-btn');
const weekViewBtn = document.getElementById('week-view-btn');
const dayViewBtn = document.getElementById('day-view-btn');
const scheduleViewBtn = document.getElementById('schedule-view-btn');

// 日历导航按钮
const prevMonthBtn = document.getElementById('prev-month-btn');
const todayBtn = document.getElementById('today-btn');
const nextMonthBtn = document.getElementById('next-month-btn');
const currentMonthSpan = document.getElementById('current-month');

// 添加任务按钮
const addTaskBtn = document.getElementById('add-task-btn');
// 关闭模态窗口
function closeTaskModal() {
    taskEditModal.style.display = 'none';
}
// 取消按钮点击事件
taskCancelBtn.addEventListener('click', closeTaskModal);

// 添加任务按钮点击事件
addTaskBtn.addEventListener('click', () => {
    const today = new Date();
    const formattedDate = today.toISOString().split('T')[0];
    openAddTaskModal(formattedDate);
});
// 处理视图切换
monthViewBtn.addEventListener('click', () => {
    // 如果当前在日程视图，需要恢复日历
    if (scheduleViewBtn.classList.contains('active')) {
        const calendarViewEl = document.getElementById('calendar-view');
        calendarViewEl.innerHTML = '';
        calendar.render();
    }

    calendar.changeView('dayGridMonth');
    updateViewButtons('month');
    // 更新后延迟调整大小并刷新事件
    setTimeout(() => {
        calendar.updateSize();
        refreshEvents();
    }, 50);
});

weekViewBtn.addEventListener('click', () => {
    // 如果当前在日程视图，需要恢复日历
    if (scheduleViewBtn.classList.contains('active')) {
        const calendarViewEl = document.getElementById('calendar-view');
        calendarViewEl.innerHTML = '';
        calendar.render();
    }

    calendar.changeView('timeGridWeek');
    updateViewButtons('week');
    // 更新后延迟调整大小并刷新事件
    setTimeout(() => {
        calendar.updateSize();
        refreshEvents();
        ensureScrollable('week');
    }, 50);
});

dayViewBtn.addEventListener('click', () => {
    // 如果当前在日程视图，需要恢复日历
    if (scheduleViewBtn.classList.contains('active')) {
        const calendarViewEl = document.getElementById('calendar-view');
        calendarViewEl.innerHTML = '';
        calendar.render();
    }

    calendar.changeView('timeGridDay');
    updateViewButtons('day');
    // 更新后延迟调整大小并刷新事件
    setTimeout(() => {
        calendar.updateSize();
        refreshEvents();
        ensureScrollable('day');
    }, 50);
});

// 确保视图可滚动并显示当前时间
function ensureScrollable(viewType) {
    // 获取所有可能需要滚动的元素
    const scrollElements = document.querySelectorAll('.fc-scroller, .fc-timegrid-body, .fc-timegrid-slots');

    // 为所有元素设置overflow: auto
    scrollElements.forEach(el => {
        el.style.overflow = 'auto';
        el.style.maxHeight = 'none';
    });

    // 滚动到当前时间位置
    const now = new Date();
    const currentHour = now.getHours();

    // 计算滚动位置：30px为每个时间格的近似高度，减去3个小时以便在当前时间前显示一些内容
    const startHour = Math.max(0, currentHour - 3);
    const scrollPosition = startHour * 60; // 大致计算滚动位置

    // 尝试所有可能的滚动容器
    scrollElements.forEach(el => {
        try {
            el.scrollTop = scrollPosition;
        } catch (e) {
            // 忽略滚动错误
            console.log('Scroll error:', e);
        }
    });
}
// 日程按钮点击事件
scheduleViewBtn.addEventListener('click', () => {
    // 隐藏日历视图，显示日程视图
    renderScheduleView();
    updateViewButtons('schedule');
});
// 渲染日程视图
function renderScheduleView() {
    // 获取日历主容器
    const calendarViewEl = document.getElementById('calendar-view');

    // 备份当前视图，保存原有内容
    const currentViewBackup = calendarViewEl.innerHTML;

    // 清空日历视图
    calendarViewEl.innerHTML = '';

    // 创建日程视图容器
    const scheduleContainer = document.createElement('div');
    scheduleContainer.className = 'schedule-view-container';
    scheduleContainer.style.height = '100%';
    scheduleContainer.style.overflowY = 'auto';
    scheduleContainer.style.padding = '15px';

    // 获取所有未完成的任务并按日期排序
    const today = new Date();
    today.setHours(0, 0, 0, 0);

    const sortedTasks = [...tasks]
        .sort((a, b) => new Date(a.start) - new Date(b.start));

    // 按日期对任务进行分组
    const tasksByDate = {};

    sortedTasks.forEach(task => {
        const taskDate = new Date(task.start);
        const dateStr = taskDate.toLocaleDateString();

        if (!tasksByDate[dateStr]) {
            tasksByDate[dateStr] = [];
        }

        tasksByDate[dateStr].push(task);
    });

    // 处理没有任务的情况
    if (Object.keys(tasksByDate).length === 0) {
        const emptyMessage = document.createElement('div');
        emptyMessage.className = 'schedule-empty-state';
        emptyMessage.innerHTML = `
            <i class="fas fa-calendar-times" style="font-size: 48px; color: #ccc; margin-bottom: 15px;"></i>
            <p style="font-size: 16px; color: #999;">暂无日程安排</p>
        `;
        emptyMessage.style.display = 'flex';
        emptyMessage.style.flexDirection = 'column';
        emptyMessage.style.alignItems = 'center';
        emptyMessage.style.justifyContent = 'center';
        emptyMessage.style.height = '100%';
        emptyMessage.style.padding = '50px 0';

        scheduleContainer.appendChild(emptyMessage);
    } else {
        // 按日期创建日程视图
        Object.keys(tasksByDate)
            .sort((a, b) => new Date(a) - new Date(b))
            .forEach(dateStr => {
                const dateSection = document.createElement('div');
                dateSection.className = 'schedule-date-section';
                dateSection.style.marginBottom = '25px';

                // 日期标题
                const dateHeader = document.createElement('h3');
                dateHeader.textContent = formatDateHeader(dateStr);
                dateHeader.style.borderBottom = '1px solid #ddd';
                dateHeader.style.paddingBottom = '8px';
                dateHeader.style.marginBottom = '10px';
                dateHeader.style.color = 'var(--primary-300)';

                dateSection.appendChild(dateHeader);

                // 该日期下的任务
                const dateTasks = tasksByDate[dateStr];

                // 按时间排序
                dateTasks.sort((a, b) => new Date(a.start) - new Date(b.start));

                dateTasks.forEach(task => {
                    const taskItem = document.createElement('div');
                    taskItem.className = 'schedule-task-item';
                    taskItem.dataset.id = task.id;

                    // 设置样式
                    taskItem.style.display = 'flex';
                    taskItem.style.alignItems = 'flex-start';
                    taskItem.style.padding = '10px 15px';
                    taskItem.style.marginBottom = '8px';
                    taskItem.style.backgroundColor = 'var(--bg-100)';
                    taskItem.style.borderRadius = '6px';
                    taskItem.style.borderLeft = `4px solid ${task.backgroundColor || '#68a67d'}`;
                    taskItem.style.cursor = 'pointer';
                    taskItem.style.transition = 'transform 0.2s ease, box-shadow 0.2s ease';

                    // 如果任务已完成，添加一些样式
                    if (task.completed) {
                        taskItem.style.opacity = '0.7';
                        taskItem.style.backgroundColor = 'var(--bg-300)';
                    }

                    // 鼠标悬停效果
                    taskItem.addEventListener('mouseenter', () => {
                        taskItem.style.transform = 'translateY(-2px)';
                        taskItem.style.boxShadow = '0 4px 8px rgba(0, 0, 0, 0.1)';
                    });

                    taskItem.addEventListener('mouseleave', () => {
                        taskItem.style.transform = 'translateY(0)';
                        taskItem.style.boxShadow = 'none';
                    });

                    // 任务内容
                    const startDate = new Date(task.start);
                    const endDate = new Date(task.end);

                    let timeDisplay = '';
                    if (task.allDay) {
                        timeDisplay = '全天';
                    } else {
                        const startTime = startDate.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: false });
                        const endTime = endDate.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: false });
                        timeDisplay = `${startTime} - ${endTime}`;
                    }

                    // 创建任务内容
                    taskItem.innerHTML = `
                        <div style="flex: 0 0 70px; color: var(--text-200); font-size: 14px;">${timeDisplay}</div>
                        <div style="flex: 1;">
                            <div style="font-weight: bold; color: var(--text-100); margin-bottom: 4px; ${task.completed ? 'text-decoration: line-through; color: #888;' : ''}">${task.title}</div>
                            ${task.description ? `<div style="font-size: 14px; color: var(--text-200); margin-bottom: 4px; ${task.completed ? 'text-decoration: line-through; color: #888;' : ''}">${task.description}</div>` : ''}
                        </div>
                        <div style="margin-left: 10px;">
                            <input type="checkbox" class="task-complete-checkbox" ${task.completed ? 'checked' : ''} style="width: 18px; height: 18px; cursor: pointer;">
                        </div>
                    `;

                    // 添加点击事件处理
                    taskItem.addEventListener('click', (e) => {
                        // 忽略复选框点击
                        if (e.target.classList.contains('task-complete-checkbox')) {
                            return;
                        }

                        const event = calendar.getEventById(task.id);
                        if (event) {
                            openEditTaskModal(event);
                        }
                    });

                    // 处理复选框点击
                    const checkbox = taskItem.querySelector('.task-complete-checkbox');
                    checkbox.addEventListener('click', (e) => {
                        e.stopPropagation();
                        toggleTaskComplete(task.id, checkbox.checked);//更新任务状态
                        // 更新任务项样式
                        if (checkbox.checked) {
                            taskItem.style.opacity = '0.7';
                            taskItem.style.backgroundColor = 'var(--bg-200)';
                            taskItem.querySelector('div div:first-child').style.textDecoration = 'line-through';
                            taskItem.querySelector('div div:first-child').style.color = '#888';
                            if (taskItem.querySelector('div div:nth-child(2)')) {
                                taskItem.querySelector('div div:nth-child(2)').style.textDecoration = 'line-through';
                                taskItem.querySelector('div div:nth-child(2)').style.color = '#888';
                            }
                        } else {
                            taskItem.style.opacity = '1';
                            taskItem.style.backgroundColor = 'var(--bg-100)';
                            taskItem.querySelector('div div:first-child').style.textDecoration = 'none';
                            taskItem.querySelector('div div:first-child').style.color = 'var(--text-100)';
                            if (taskItem.querySelector('div div:nth-child(2)')) {
                                taskItem.querySelector('div div:nth-child(2)').style.textDecoration = 'none';
                                taskItem.querySelector('div div:nth-child(2)').style.color = 'var(--text-200)';
                            }
                        }
                    });

                    dateSection.appendChild(taskItem);
                });

                scheduleContainer.appendChild(dateSection);
            });
    }

    calendarViewEl.appendChild(scheduleContainer);

    // 添加返回日历视图的处理
    scheduleViewBtn.setAttribute('data-view-backup', currentViewBackup);

    // 辅助函数：格式化日期标题
    function formatDateHeader(dateStr) {
        const date = new Date(dateStr);
        const now = new Date();
        now.setHours(0, 0, 0, 0);

        const tomorrow = new Date(now);
        tomorrow.setDate(now.getDate() + 1);

        const yesterday = new Date(now);
        yesterday.setDate(now.getDate() - 1);

        if (date.toDateString() === now.toDateString()) {
            return `今天（${date.toLocaleDateString()}）`;
        } else if (date.toDateString() === tomorrow.toDateString()) {
            return `明天（${date.toLocaleDateString()}）`;
        } else if (date.toDateString() === yesterday.toDateString()) {
            return `昨天（${date.toLocaleDateString()}）`;
        } else {
            return date.toLocaleDateString();
        }
    }
}
// 刷新日历事件
function refreshEvents() {
    // 先移除所有事件
    calendar.getEvents().forEach(event => event.remove());

    // 重新添加所有事件
    tasks.forEach(task => {
        calendar.addEvent(task);
    });
}

// 处理日历导航
prevMonthBtn.addEventListener('click', () => {
    // 如果当前在日程视图，需要恢复日历
    if (scheduleViewBtn.classList.contains('active')) {
        const calendarViewEl = document.getElementById('calendar-view');
        calendarViewEl.innerHTML = '';
        calendar.render();
    }
    calendar.prev();
});

todayBtn.addEventListener('click', () => {
    // 如果当前在日程视图，需要恢复日历
    if (scheduleViewBtn.classList.contains('active')) {
        const calendarViewEl = document.getElementById('calendar-view');
        calendarViewEl.innerHTML = '';
        calendar.render();
    }
    calendar.today();
});

nextMonthBtn.addEventListener('click', () => {
    // 如果当前在日程视图，需要恢复日历
    if (scheduleViewBtn.classList.contains('active')) {
        const calendarViewEl = document.getElementById('calendar-view');
        calendarViewEl.innerHTML = '';
        calendar.render();
    }
    calendar.next();
});

// 更新视图按钮状态
function updateViewButtons(activeView) {
    monthViewBtn.classList.remove('active');
    weekViewBtn.classList.remove('active');
    dayViewBtn.classList.remove('active');
    scheduleViewBtn.classList.remove('active');

    switch (activeView) {
        case 'month':
            monthViewBtn.classList.add('active');
            break;
        case 'week':
            weekViewBtn.classList.add('active');
            break;
        case 'day':
            dayViewBtn.classList.add('active');
            break;
        case 'schedule':
            scheduleViewBtn.classList.add('active');
            break;
    }
}

/**
 * 初始化任务管理模块
 */
function initialize() {
    console.log('初始化任务管理模块...');

    if(calendar){
        calendar.updateSize();
    }
    if (isInitialized) {
        console.log('任务管理模块已经初始化');
        return;
    }

    try {
        // 确保DOM已经加载完成
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => {
                initializeModule();
            });
        } else {
            initializeModule();
        }
    } catch (error) {
        handleError('初始化任务管理模块失败', ErrorTypes.APPLICATION, { error });
        showNotification('初始化失败，请刷新页面重试', 'error');
    }
}

/**
 * 实际的初始化函数
 */
function initializeModule() {
    try {
        // 检查必要的DOM元素是否存在
        const requiredElements = [
            'calendar-view',
            'task-edit-modal',
            'task-form'
        ];

        const missingElements = requiredElements.filter(id => !document.getElementById(id));
        if (missingElements.length > 0) {
            throw new Error(`缺少必要的DOM元素: ${missingElements.join(', ')}`);
        }

        // 初始化日历相关变量
        const calendarEl = document.getElementById('calendar-view');
        if (!calendarEl) {
            throw new Error('找不到日历容器元素');
        }

        // 检查FullCalendar是否可用
        if (typeof FullCalendar === 'undefined') {
            throw new Error('FullCalendar库未加载');
        }

        // 加载任务数据
        loadTasks();

        // // 初始化工具栏
        // initializeToolbar();

        // 创建日历实例
        initializeCalendar(calendarEl);

        // 设置事件监听,监听按钮,主页监听
        setupEventListeners();

        // 标记为已初始化
        isInitialized = true;
        // 更新任务统计数据
        updateTaskStats();

        console.log('任务管理模块初始化完成');
    } catch (error) {
        handleError('初始化任务管理模块失败', ErrorTypes.APPLICATION, { error });
        showNotification('初始化失败，请刷新页面重试', 'error');
    }
}

/**
 * 初始化工具栏
 */
function initializeToolbar() {
    const toolbar = document.getElementById('calendar-toolbar');
    if (!toolbar) return;

    toolbar.innerHTML = `
        <div class="calendar-controls">
            <div class="view-controls">
                <button class="view-btn" data-view="dayGridMonth">月</button>
                <button class="view-btn" data-view="timeGridWeek">周</button>
                <button class="view-btn" data-view="timeGridDay">日</button>
                <button class="view-btn" data-view="listWeek">日程</button>
            </div>
            <div class="navigation-controls">
                <button class="nav-btn prev" title="上一个">
                    <i class="fas fa-chevron-left"></i>
                </button>
                <button class="nav-btn today" title="今天">今天</button>
                <button class="nav-btn next" title="下一个">
                    <i class="fas fa-chevron-right"></i>
                </button>
                <span class="current-date"></span>
            </div>
            <div class="action-controls">
                <button class="btn-add" title="添加待办">
                    <i class="fas fa-plus"></i> 添加待办
                </button>
            </div>
        </div>
    `;

    // 绑定工具栏事件
    bindToolbarEvents();
}

/**
 * 初始化日历
 */
function initializeCalendar(calendarEl) {
    calendar = new FullCalendar.Calendar(calendarEl, {
        initialView: currentView,
        headerToolbar: false, // 使用自定义工具栏
        firstDay: 1, // 周一开始
        dayMaxEvents: 3,
        eventTimeFormat: {
            hour: '2-digit',
            minute: '2-digit',
            hour12: false
        },
        timeZone: 'local',
        aspectRatio: 1.8,
        expandRows: true,
        events: tasks,
        locale: 'zh-CN',
        eventClassNames: function (arg) {
            return arg.event.extendedProps.completed ? ['completed-event'] : [];
        },
        eventClick: function (info) {
            openEditTaskModal(info.event);
        },
        dateClick: function (info) {
            openAddTaskModal(info.dateStr);
        },
        datesSet: function (info) {
            updateCurrentMonthDisplay(info.view);
            updateToolbarState(info.view);
        },
        dayRender: function(info) {// 渲染每个日期单元格
            // 检查是否是今天
            const today = new Date();
            //格式化今天的日期
            const formattedToday = today.toISOString().split('T')[0];
            if (info.dateStr === formattedToday) {
                // 为今天添加自定义CSS类
                info.el.classList.add('today');
            }
            
        },
        nowIndicator: true,
        eventDisplay: 'block',
        eventColor: '#68a67d',
        longPressDelay: 100,
        editable: false,
        droppable: false,
        slotDuration: '00:30:00',
        slotMinTime: '00:00:00',
        slotMaxTime: '24:00:00',
        scrollTime: '07:00:00',
        slotEventOverlap: false,
        handleWindowResize: true,
        height: '100%',
        contentHeight: 'auto',
        allDaySlot: true,
        allDayText: '全天',
        eventContent: formatEventContent,
        eventDidMount: handleEventMount
    });

    // 渲染日历
    calendar.render();

    // 确保日历大小正确
    setTimeout(() => {
        calendar.updateSize();
    }, 2000);
}

/**
 * 绑定工具栏事件
 */
function bindToolbarEvents() {
    const toolbar = document.getElementById('calendar-toolbar');
    if (!toolbar) return;

    // 视图切换
    toolbar.querySelectorAll('.view-btn').forEach(btn => {
        btn.addEventListener('click', () => {
            const view = btn.dataset.view;
            if (calendar && view) {
                currentView = view;
                calendar.changeView(view);
                updateToolbarState({ type: view });
            }
        });
    });

    // 导航按钮
    const prevBtn = toolbar.querySelector('.nav-btn.prev');
    const nextBtn = toolbar.querySelector('.nav-btn.next');
    const todayBtn = toolbar.querySelector('.nav-btn.today');

    if (prevBtn) {
        prevBtn.addEventListener('click', () => calendar?.prev());
    }
    if (nextBtn) {
        nextBtn.addEventListener('click', () => calendar?.next());
    }
    if (todayBtn) {
        todayBtn.addEventListener('click', () => calendar?.today());
    }

    // 添加待办按钮
    const addBtn = toolbar.querySelector('.btn-add');
    if (addBtn) {
        addBtn.addEventListener('click', () => {
            openAddTaskModal();
        });
    }
}
// 更新当前月份/年份显示
function updateCurrentMonthDisplay(view) {
    if (currentMonthSpan) {
        const title = view.title;
        currentMonthSpan.textContent = title;
    }
}
// 打开添加任务对话框
function openAddTaskModal(dateStr) {
    // 重置表单
    taskForm.reset();

    // 设置默认值
    taskForm.dataset.taskId = '';
    taskDate.value = dateStr;
    const now = new Date();
    taskStartTime.value = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
    now.setHours(now.getHours() + 1);
    taskEndTime.value = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
    taskColor.value = '#68a67d'; // 默认绿色
    taskCompleted.checked = false; // 默认未完成

    // 更新模态窗口标题和按钮
    taskModalTitle.textContent = '添加待办事项';
    taskDeleteBtn.style.display = 'none';
    currentTaskId = null;

    // 显示模态窗口
    taskEditModal.style.display = 'flex';
}
// 打开编辑任务对话框
function openEditTaskModal(event) {
    const task = event.extendedProps;
    currentTaskId = event.id;
    const form = document.getElementById('task-form');
    form.dataset.taskId = event.id;
    const taskTitle = document.getElementById('task-title');
    const taskDescription = document.getElementById('task-description');

    // 填充表单
    taskTitle.value = event.title;
    taskDescription.value = task.description || '';

    // 设置日期和时间
    const startDate = event.start ? new Date(event.start) : new Date();
    const endDate = event.end ? new Date(event.end) : new Date(startDate.getTime() + 3600000);

    taskDate.value = startDate.toISOString().split('T')[0];

    if (event.allDay) {
        taskStartTime.value = '';
        taskEndTime.value = '';
    } else {
        taskStartTime.value = `${String(startDate.getHours()).padStart(2, '0')}:${String(startDate.getMinutes()).padStart(2, '0')}`;
        taskEndTime.value = `${String(endDate.getHours()).padStart(2, '0')}:${String(endDate.getMinutes()).padStart(2, '0')}`;
    }

    taskColor.value = event.backgroundColor || '#68a67d';
    taskCompleted.checked = task.completed || false;
    taskNotification.checked = task.notification !== undefined ? task.notification : true;

    // 更新模态窗口标题和按钮
    taskModalTitle.textContent = '编辑待办事项';
    taskDeleteBtn.style.display = 'block';

    // 显示模态窗口
    taskEditModal.style.display = 'flex';
}

// 删除任务按钮点击事件
taskDeleteBtn.addEventListener('click', () => {
    if (currentTaskId) {
        if (confirm('确定要删除此待办事项吗？')) {
            // 从通知记录中移除
            notifiedTaskIds.delete(currentTaskId);
            notifiedTaskIds.delete(`${currentTaskId}_started`);

            // 从任务列表中移除
            tasks = tasks.filter(task => task.id !== currentTaskId);

            // 从日历中移除
            const event = calendar.getEventById(currentTaskId);
            if (event) {
                event.remove();
            }

            // 保存到本地存储
            saveTasks();

            // 更新任务列表
            updateTasksDisplay();


            // 如果当前处于日程视图，刷新日程视图
            if (scheduleViewBtn.classList.contains('active')) {
                renderScheduleView();
            }

            // 关闭模态窗口
            hideTaskModal();

            // 显示提示
            showToast('待办事项已删除', 'success');
        }
    }
});
/**
 * 更新工具栏状态
 */
function updateToolbarState(view) {
    const toolbar = document.getElementById('calendar-toolbar');
    if (!toolbar) return;

    // 更新视图按钮状态
    toolbar.querySelectorAll('.view-btn').forEach(btn => {
        btn.classList.toggle('active', btn.dataset.view === view.type);
    });

    // 更新当前日期显示
    const dateDisplay = toolbar.querySelector('.current-date');
    if (dateDisplay) {
        dateDisplay.textContent = formatDateForDisplay(calendar.getDate());
    }
}

/**
 * 格式化事件内容
 */
function formatEventContent(arg) {
    let content = arg.event.title;

    if (!arg.event.allDay && arg.event.start) {
        const start = new Date(arg.event.start);
        const end = new Date(arg.event.end || start);
        const startTimeStr = start.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: false });
        const endTimeStr = end.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: false });
        let timeStr = `${startTimeStr} - ${endTimeStr}`;

        if (arg.view.type === 'dayGridMonth') {
            timeStr = startTimeStr;
        }

        return {
            html: `<div class="fc-event-time">${timeStr}</div>
                   <div class="fc-event-title">${content}</div>`
        };
    }

    return { html: `<div class="fc-event-title">${content}</div>` };
}

/**
 * 处理事件挂载
 */
function handleEventMount(arg) {
    if (arg.view.type === 'dayGridMonth') {
        const timeElement = arg.el.querySelector('.fc-event-time');
        if (timeElement) {
            timeElement.style.display = 'inline-block';
            timeElement.style.marginRight = '4px';
            timeElement.style.marginTop = '2.5px';
        }

        const titleElement = arg.el.querySelector('.fc-event-title');
        if (titleElement) {
            titleElement.style.display = 'inline-block';
            titleElement.style.overflow = 'hidden';
            titleElement.style.textOverflow = 'ellipsis';
            titleElement.style.whiteSpace = 'nowrap';
            titleElement.style.maxWidth = 'calc(100% - 45px)';
        }
    }

    // 确保日历大小正确
    calendar?.updateSize();
}

/**
 * 设置页面导航
 */
function setupPageNavigation() {
    // 监听 hashchange 事件
    window.addEventListener('hashchange', handleHashChange);

    // 初始化时检查 hash
    handleHashChange();
}

/**
 * 处理 hash 变化
 */
function handleHashChange() {
    const hash = window.location.hash;
    const pages = document.querySelectorAll('.page');

    pages.forEach(page => {
        if (page.dataset.page === hash.slice(1)) {
            page.classList.add('active');
        } else {
            page.classList.remove('active');
        }
    });
}

/**
 * 加载任务数据
 */
function loadTasks() {
    try {
        const savedTasks = localStorage.getItem('calendarTasks');
        if (savedTasks) {
            tasks = JSON.parse(savedTasks);
            updateTasksDisplay();
        }
    } catch (error) {
        handleError('加载任务数据失败', ErrorTypes.DATA, { error });
        showNotification('加载任务数据失败，将使用空数据', 'warning');
        tasks = [];
    }
}

/**
 * 设置事件监听器
 */
function setupEventListeners() {
    try {
        // 主页面的"查看全部"链接
        const viewAllLinks = document.querySelectorAll('a[href="#calendar"].view-all');
        viewAllLinks.forEach(link => {
            link.addEventListener('click', (e) => {
                e.preventDefault();
                navigateToCalendar();
            });
        });

        // 主页面的"添加待办"按钮
        const quickAddTaskBtns = document.querySelectorAll('.quick-add-task');
        quickAddTaskBtns.forEach(btn => {
            btn.addEventListener('click', () => {
                showTaskModal();
            });
        });

        // 任务编辑模态框
        const taskModal = document.getElementById('task-edit-modal');
        if (taskModal) {
            // 保存按钮
            const saveBtn = taskModal.querySelector('#task-save-btn');
            if (saveBtn) {
                saveBtn.addEventListener('click', (e) => {
                    e.preventDefault();
                    saveTask();
                });
            }

            // 取消按钮
            const cancelBtn = taskModal.querySelector('#task-cancel-btn');
            if (cancelBtn) {
                cancelBtn.addEventListener('click', () => {
                    hideTaskModal();
                });
            }
        }

        // 添加键盘事件监听
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') {
                hideTaskModal();
            }
        });

    } catch (error) {
        handleError('设置事件监听器失败', ErrorTypes.APPLICATION, { error });
    }
}

/**
 * 导航到日历页面
 */
function navigateToCalendar() {
    const calendarPage = document.querySelector('.page[data-page="calendar"]');
    if (calendarPage) {
        document.querySelectorAll('.page').forEach(page => {
            page.classList.remove('active');
        });
        calendarPage.classList.add('active');
        window.location.hash = '#calendar';
        updateTasksDisplay();
    }
}

/**
 * 显示任务编辑模态框
 */
function showTaskModal(task = null) {
    const modal = document.getElementById('task-edit-modal');
    const form = document.getElementById('task-form');

    if (!modal || !form) {
        console.error('找不到任务编辑模态框或表单');
        return;
    }

    // 重置表单
    form.reset();

    // 如果是编辑任务，填充表单
    if (task) {
        document.getElementById('task-title').value = task.title || '';
        document.getElementById('task-description').value = task.description || '';
        document.getElementById('task-date').value = formatDateForInput(task.date);
        document.getElementById('task-start-time').value = task.startTime || '';
        document.getElementById('task-end-time').value = task.endTime || '';
        form.dataset.taskId = task.id;
    } else {
        // 新建任务时设置默认日期为今天
        const today = new Date();
        document.getElementById('task-date').value = formatDateForInput(today);
        delete form.dataset.taskId;
    }

    // 显示模态框
    modal.style.display = 'block';
    // 聚焦标题输入框
    document.getElementById('task-title')?.focus();
}

/**
 * 隐藏任务编辑模态框
 */
function hideTaskModal() {
    // const modal = document.getElementById('task-edit-modal');
    // if (modal) {
    //     modal.classList.remove('show');
    // }
    closeTaskModal()
}

/**
 * 保存任务
 */
function saveTask() {
    // console.log('保存任务');
    const form = document.getElementById('task-form');
    const titleInput = document.getElementById('task-title');
    const dateInput = document.getElementById('task-date');
    const descriptionInput = document.getElementById('task-description');
    const startTimeInput = document.getElementById('task-start-time');
    const endTimeInput = document.getElementById('task-end-time');
    const colorInput = document.getElementById('task-color');
    const completedInput = document.getElementById('task-completed');
    const notificationInput = document.getElementById('task-notification');

    if (!form || !titleInput || !dateInput || !descriptionInput || !startTimeInput || !endTimeInput || !colorInput || !completedInput || !notificationInput) {
        console.error('找不到必要的表单元素');
        return;
    }

    const title = titleInput.value.trim();
    const description = descriptionInput.value.trim();
    const date = dateInput.value;
    const startTime = startTimeInput.value;
    const endTime = endTimeInput.value;
    const color = colorInput.value;
    const completed = completedInput.checked;
    const notification = notificationInput.checked;

    let start, end;
    if (startTime) {
        start = `${date}T${startTime}`;
        end = endTime ? `${date}T${endTime}` : start;
    } else {
        // 全天事件
        start = date;
        end = date;
    }

    const task = {
        id: form.dataset.taskId || Date.now().toString(), // 使用现有ID或生成新ID
        title,
        description,
        start,
        end,
        allDay: !startTime, // 如果没有设置开始时间，则为全天事件
        backgroundColor: color,
        borderColor: color,
        textColor: '#fff',
        extendedProps: {
            completed
        },
        completed, // 直接在顶层也存储completed状态
        notification
    };

    try {
        // 如果是编辑任务，更新现有任务
        const taskIndex = tasks.findIndex(t => t.id === task.id);
        if (taskIndex !== -1) {
            tasks[taskIndex] = { ...tasks[taskIndex], ...task };
            //刷新日历事件
        } else {
            // 否则添加新任务
            tasks.push(task);
        }
        // 添加事件到日历
        // calendar.addEvent(task);
        refreshEvents();
        // 保存到本地存储
        saveTasks();

        // 更新显示
        updateTasksDisplay();

        // 隐藏模态框
        hideTaskModal();
        // 更新任务统计数据
        updateTaskStats();
        // 显示成功提示
        showNotification('任务保存成功！');
    } catch (error) {
        handleError('保存任务失败', ErrorTypes.DATA, { error });
        showNotification('保存任务失败，请重试', 'error');
    }
}
/**
 * 更新任务统计数据
 */
function updateTaskStats() {
    // 获取所有任务
    const tasks = JSON.parse(localStorage.getItem('calendarTasks') || '[]');

    // 计算已完成和待完成任务数量
    const completedTasks = tasks.filter(task => task.completed).length;
    const pendingTasks = tasks.length - completedTasks;

    // 计算完成率
    const completionRate = tasks.length > 0 ? Math.round((completedTasks / tasks.length) * 100) : 0;

    // 获取重要任务（假设背景色为红色的是重要任务）
    const importantTasks = tasks.filter(task => task.backgroundColor === '#e74c3c' || task.backgroundColor === '#cc0000');
    const completedImportantTasks = importantTasks.filter(task => task.completed).length;
    const priorityCompletionRate = importantTasks.length > 0
        ? Math.round((completedImportantTasks / importantTasks.length) * 100)
        : 0;

    // 更新UI
    document.getElementById('completed-tasks').textContent = completedTasks;
    document.getElementById('pending-tasks').textContent = pendingTasks;
    document.getElementById('completion-rate-value').textContent = `${completionRate}%`;
    document.getElementById('priority-completion-rate').textContent = `${priorityCompletionRate}%`;

    // 更新进度条
    document.getElementById('completion-progress').style.width = `${completionRate}%`;
    document.getElementById('priority-progress').style.width = `${priorityCompletionRate}%`;
}
/**
 * 保存任务到本地存储
 */
function saveTasks() {
    try {
        localStorage.setItem('calendarTasks', JSON.stringify(tasks));
        updateTaskStats(); // 更新任务统计数据
    } catch (error) {
        handleError('保存任务数据失败', ErrorTypes.DATA, { error });
    }
}

/**
 * 更新任务显示
 */
function updateTasksDisplay() {
    try {
        // 更新快速任务列表
        updateQuickTasksList();

        // 更新任务计数
        updateTaskCount();

        // 如果在日历页面，更新日历视图
        if (window.location.hash === '#calendar') {
            updateCalendarView();
        }
    } catch (error) {
        handleError('更新任务显示失败', ErrorTypes.APPLICATION, { error });
    }
}

/**
 * 更新快速任务列表
 */
// function updateQuickTasksList() {
//     const container = document.getElementById('quick-tasks-list');
//     if (!container) return;

//     // 获取今日任务
//     const today = new Date();
//     today.setHours(0, 0, 0, 0);
//     const tomorrow = new Date(today);
//     tomorrow.setDate(tomorrow.getDate() + 1);

//     const todayTasks = tasks.filter(task => {
//         const taskDate = new Date(task.date);
//         return taskDate >= today && taskDate < tomorrow;
//     }).sort((a, b) => {
//         // 按时间排序
//         return a.startTime?.localeCompare(b.startTime) || 0;
//     });

//     if (todayTasks.length === 0) {
//         container.innerHTML = `
//             <div class="empty-tasks">
//                 <i class="fas fa-clipboard-list"></i>
//                 <p>今日暂无待办事项</p>
//             </div>
//         `;
//         return;
//     }

//     container.innerHTML = todayTasks.map(task => `
//         <div class="task-item ${task.completed ? 'completed' : ''}" data-id="${task.id}">
//             <div class="task-checkbox">
//                 <input type="checkbox" ${task.completed ? 'checked' : ''}>
//             </div>
//             <div class="task-content">
//                 <div class="task-title">${task.title}</div>
//                 <div class="task-time">${task.startTime || '全天'}</div>
//             </div>
//         </div>
//     `).join('');

//     // 添加复选框事件监听
//     container.querySelectorAll('.task-checkbox input').forEach(checkbox => {
//         checkbox.addEventListener('change', (e) => {
//             const taskId = e.target.closest('.task-item').dataset.id;
//             toggleTaskComplete(taskId);
//         });
//     });
// }
// 渲染任务列表
function updateQuickTasksList() {
    const taskList = document.getElementById('task-list');
    if (!taskList) return;

    taskList.innerHTML = '';

    // 获取所有任务
    const allTasks = tasks || [];

    // 获取今天的日期（起始时间和结束时间）
    const today = new Date();
    const startOfDay = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 0, 0, 0).getTime();
    const endOfDay = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 23, 59, 59).getTime();

    // 过滤出今天的任务
    const todayTasks = allTasks.filter(task => {
        const taskStart = new Date(task.start).getTime();
        const taskEnd = new Date(task.end).getTime();
        return (taskStart >= startOfDay && taskStart <= endOfDay) ||
            (taskEnd >= startOfDay && taskEnd <= endOfDay) ||
            (taskStart <= startOfDay && taskEnd >= endOfDay);
    });

    // 对任务进行排序：先按照完成状态，再按照开始时间
    const sortedTasks = todayTasks.sort((a, b) => {
        // 首先按照完成状态排序（未完成的在前）
        if (a.completed !== b.completed) {
            return a.completed ? 1 : -1;
        }

        // 然后按照开始时间排序
        return new Date(a.start) - new Date(b.start);
    });

    if (sortedTasks.length === 0) {
        taskList.innerHTML = `
            <div class="task-empty-state">
                <i class="fas fa-clipboard-list"></i>
                <p>今日暂无待办事项</p>
            </div>
        `;
        return;
    }

    // 创建任务列表项
    sortedTasks.forEach(task => {
        // ... 原有代码，创建任务列表项
        const taskItem = document.createElement('div');
        taskItem.className = 'task-item';
        taskItem.dataset.id = task.id;

        // 如果任务已完成，添加completed类
        if (task.completed) {
            taskItem.classList.add('completed');
        }

        const startDate = new Date(task.start);
        const endDate = new Date(task.end);
        const formattedDate = startDate.toLocaleDateString();

        let formattedTime = '';
        if (task.allDay) {
            formattedTime = '全天';
        } else {
            const startTime = startDate.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: false });
            const endTime = endDate.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: false });
            formattedTime = `${startTime}-${endTime}`;
        }

        // 创建任务内容
        taskItem.innerHTML = `
            <input type="checkbox" class="task-complete-checkbox" ${task.completed ? 'checked' : ''}>
            <div class="task-color-indicator" style="background-color: ${task.backgroundColor || '#68a67d'}"></div>
            <div class="task-content">
                <div class="task-title">${task.title}</div>
                ${task.description ? `<div class="task-description">${task.description}</div>` : ''}
                <div class="task-time">
                    <i class="fas fa-calendar-day"></i>
                    ${formattedDate} ${formattedTime}
                </div>
            </div>
        `;

        // 设置任务项的左边框颜色
        taskItem.style.borderLeftColor = task.backgroundColor || '#68a67d';

        // 获取复选框元素
        const checkbox = taskItem.querySelector('.task-complete-checkbox');

        // 阻止复选框点击事件冒泡
        checkbox.addEventListener('click', (e) => {
            e.stopPropagation();
            const completed = checkbox.checked;
            toggleTaskComplete(task.id, completed);
        });

        // 点击任务项打开编辑对话框
        taskItem.addEventListener('click', (e) => {
            // 如果点击的是复选框，不打开编辑对话框
            if (e.target !== checkbox) {
                const event = calendar.getEventById(task.id);
                if (event) {
                    openEditTaskModal(event);
                }
            }
        });

        taskList.appendChild(taskItem);
    });
}

/**
 * 更新任务计数
 */
function updateTaskCount() {
    const tasksList = document.getElementById('quick-tasks-list');
    if (!tasksList) return;

    // 获取今日待办
    const now = new Date();
    const startOfDay = new Date().getTime();
    const endOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59).getTime();

    const tasks = JSON.parse(localStorage.getItem('calendarTasks') || '[]');
    let todayTasksCount = 0;
    const todayTasks = tasks.filter(task => {
        const taskStartTime = new Date(task.start).getTime();
        const taskEndTime = new Date(task.end).getTime();
        // 任务在今天开始或正在进行中
        if ((taskStartTime >= startOfDay && taskStartTime < endOfDay) || 
            (taskStartTime <= startOfDay && taskEndTime >= startOfDay)) {
            todayTasksCount++;
        }
        // 返回今天开始或正在进行的任务
        return (taskStartTime >= startOfDay && taskStartTime < endOfDay) || 
               (taskStartTime <= startOfDay && taskEndTime >= startOfDay);
    }).sort((a, b) => new Date(a.start) - new Date(b.start)).slice(0, 3); // 只显示前3个任务
    // console.log('todayTasks', tasks.sort((a, b) => new Date(a.start) - new Date(b.start)), todayTasksCount, todayTasks);
    document.getElementById('today-tasks-count').textContent = todayTasksCount;

    if (todayTasks.length === 0) {
        tasksList.innerHTML = `
            <div class="task-empty">
                <p>今日暂无待办事项</p>
            </div>
        `;
        return;
    }

    tasksList.innerHTML = todayTasks.map(task => `
        <div class="task-item-index task-item ${task.completed ? 'completed' : ''}" data-id="${task.id}">
            <div class="task-checkbox">
                ${task.completed ?
            '<i class="fas fa-check-circle"></i>' :
            '<i class="far fa-circle"></i>'}
            </div>
            <div class="task-content">
                <div class="task-title">${task.title}</div>
                <div class="task-time">${new Date(task.start).toLocaleTimeString('zh-CN', {
                hour: '2-digit',
                minute: '2-digit'
            })}</div>
            </div>
        </div>
    `).join('');

    // 绑定任务点击事件
    tasksList.querySelectorAll('.task-item-index').forEach(item => {
        item.addEventListener('click', () => {
            const taskId = item.dataset.id;
            const task = tasks.find(t => t.id === taskId);
            console.log('task', task);
            if (task && !task.completed) {
                // 完成这个待办
                if (confirm('确定要完成这个待办吗？')) {
                    const taskIndex = tasks.findIndex(t => t.id === taskId);
                    if (taskIndex !== -1) {
                        tasks[taskIndex].completed = true;
                    }
                    localStorage.setItem('calendarTasks', JSON.stringify(tasks));
                    updateTaskCount();
                }
            }
        });
    });
}

/**
 * 切换任务完成状态
 * @param {string} taskId - 任务ID
 */
function toggleTaskComplete(taskId) {
    const task = tasks.find(t => t.id === taskId);
    if (task) {
        task.completed = !task.completed;
        saveTasks();
        updateTasksDisplay();
    }
}

/**
 * 格式化日期为输入框格式
 * @param {string} date - 日期字符串
 * @returns {string} 格式化后的日期字符串
 */
function formatDateForInput(date) {
    return new Date(date).toISOString().split('T')[0];
}



/**
 * 显示通知
 */
function showNotification(message, type = 'info') {
    showToast(message, type);
}

/**
 * 更新日历视图
 */
function updateCalendarView() {
    const calendarContainer = document.getElementById('calendar-container');
    if (!calendarContainer) {
        console.warn('未找到日历容器元素');
        return;
    }

    try {
        // 生成日历视图切换器
        const viewSwitcher = `
            <div class="calendar-view-switcher">
                <button class="view-btn ${currentView === CalendarViewType.MONTH ? 'active' : ''}" 
                        data-view="${CalendarViewType.MONTH}">月视图</button>
                <button class="view-btn ${currentView === CalendarViewType.WEEK ? 'active' : ''}" 
                        data-view="${CalendarViewType.WEEK}">周视图</button>
                <button class="view-btn ${currentView === CalendarViewType.DAY ? 'active' : ''}" 
                        data-view="${CalendarViewType.DAY}">日视图</button>
                <button class="view-btn ${currentView === CalendarViewType.SCHEDULE ? 'active' : ''}" 
                        data-view="${CalendarViewType.SCHEDULE}">日程</button>
            </div>
            <div class="calendar-navigation">
                <button class="nav-btn prev"><i class="fas fa-chevron-left"></i></button>
                <span class="current-date">${formatDateForDisplay(currentDate)}</span>
                <button class="nav-btn next"><i class="fas fa-chevron-right"></i></button>
                <button class="nav-btn today">今天</button>
            </div>
        `;

        // 生成日历内容
        let calendarContent = '';
        switch (currentView) {
            case CalendarViewType.MONTH:
                calendarContent = generateMonthView();
                break;
            case CalendarViewType.WEEK:
                calendarContent = generateWeekView();
                break;
            case CalendarViewType.DAY:
                calendarContent = generateDayView();
                break;
            case CalendarViewType.SCHEDULE:
                calendarContent = generateScheduleView();
                break;
        }

        // 更新容器内容
        calendarContainer.innerHTML = `
            <div class="calendar-header">
                <h2>日历待办</h2>
                <div class="calendar-controls">
                    ${viewSwitcher}
                </div>
                <button class="btn-add" id="calendar-add-task">
                    <i class="fas fa-plus"></i> 添加待办
                </button>
            </div>
            <div class="calendar-body">
                ${calendarContent}
            </div>
        `;

        // 绑定事件
        bindCalendarEvents();
    } catch (error) {
        handleError('更新日历视图失败', ErrorTypes.APPLICATION, { error });
        showNotification('更新日历视图失败', 'error');
    }
}

/**
 * 生成月视图
 */
function generateMonthView() {
    const year = currentDate.getFullYear();
    const month = currentDate.getMonth();
    const firstDay = new Date(year, month, 1);
    const lastDay = new Date(year, month + 1, 0);
    const startDate = new Date(firstDay);
    startDate.setDate(startDate.getDate() - startDate.getDay());

    let html = `
        <div class="calendar-grid month-view">
            <div class="calendar-weekdays">
                ${['日', '一', '二', '三', '四', '五', '六']
            .map(day => `<div class="weekday">${day}</div>`).join('')}
            </div>
            <div class="calendar-days">
    `;

    const today = new Date();
    today.setHours(0, 0, 0, 0);

    for (let i = 0; i < 42; i++) {
        const date = new Date(startDate);
        date.setDate(startDate.getDate() + i);
        const isToday = date.getTime() === today.getTime();
        const isCurrentMonth = date.getMonth() === month;
        const dateStr = formatDateForInput(date);
        const dayTasks = tasks.filter(task => task.date === dateStr);

        html += `
            <div class="calendar-day ${isToday ? 'today' : ''} ${isCurrentMonth ? 'current-month' : 'other-month'}"
                 data-date="${dateStr}">
                <div class="day-header">
                    <span class="day-number">${date.getDate()}</span>
                    ${dayTasks.length > 0 ? `<span class="task-count">${dayTasks.length}</span>` : ''}
                </div>
                <div class="day-content">
                    ${dayTasks.slice(0, 3).map(task => `
                        <div class="task-item mini ${task.completed ? 'completed' : ''}" 
                             data-id="${task.id}" title="${task.title}">
                            <span class="task-title">${task.title}</span>
                        </div>
                    `).join('')}
                    ${dayTasks.length > 3 ? `
                        <div class="more-tasks">+${dayTasks.length - 3}个待办</div>
                    ` : ''}
                </div>
            </div>
        `;
    }

    html += `
            </div>
        </div>
    `;

    return html;
}

/**
 * 生成周视图
 */
function generateWeekView() {
    const startDate = new Date(currentDate);
    startDate.setDate(startDate.getDate() - startDate.getDay());
    const endDate = new Date(startDate);
    endDate.setDate(startDate.getDate() + 6);

    let html = `
        <div class="calendar-grid week-view">
            <div class="time-slots">
                ${Array.from({ length: 24 }, (_, i) =>
        `<div class="time-slot">${String(i).padStart(2, '0')}:00</div>`
    ).join('')}
            </div>
    `;

    for (let i = 0; i < 7; i++) {
        const date = new Date(startDate);
        date.setDate(startDate.getDate() + i);
        const dateStr = formatDateForInput(date);
        const dayTasks = tasks.filter(task => task.date === dateStr);

        html += `
            <div class="week-day" data-date="${dateStr}">
                <div class="day-header">
                    <div class="day-name">${['周日', '周一', '周二', '周三', '周四', '周五', '周六'][i]}</div>
                    <div class="day-number">${date.getDate()}</div>
                </div>
                <div class="day-content">
                    ${generateDaySchedule(dayTasks)}
                </div>
            </div>
        `;
    }

    html += '</div>';
    return html;
}

/**
 * 生成日视图
 */
function generateDayView() {
    const dateStr = formatDateForInput(currentDate);
    const dayTasks = tasks.filter(task => task.date === dateStr);

    return `
        <div class="calendar-grid day-view">
            <div class="time-slots">
                ${Array.from({ length: 24 }, (_, i) =>
        `<div class="time-slot">${String(i).padStart(2, '0')}:00</div>`
    ).join('')}
            </div>
            <div class="day-content">
                ${generateDaySchedule(dayTasks)}
            </div>
        </div>
    `;
}

/**
 * 生成日程视图
 */
function generateScheduleView() {
    // 获取未来30天的任务
    const startDate = new Date(currentDate);
    const endDate = new Date(currentDate);
    endDate.setDate(endDate.getDate() + 30);

    const futureTasks = tasks.filter(task => {
        const taskDate = new Date(task.date);
        return taskDate >= startDate && taskDate <= endDate;
    }).sort((a, b) => new Date(a.date) - new Date(b.date));

    if (futureTasks.length === 0) {
        return `
            <div class="empty-schedule">
                <i class="fas fa-calendar-alt"></i>
                <p>暂无待办事项</p>
            </div>
        `;
    }

    let html = '<div class="schedule-view">';
    let currentDateStr = '';

    futureTasks.forEach(task => {
        const taskDate = new Date(task.date);
        const dateStr = formatDateForDisplay(taskDate);

        if (dateStr !== currentDateStr) {
            if (currentDateStr) {
                html += '</div>';
            }
            currentDateStr = dateStr;
            html += `
                <div class="schedule-date">
                    <div class="date-header">
                        <h3>${dateStr}</h3>
                    </div>
            `;
        }

        html += `
            <div class="schedule-task ${task.completed ? 'completed' : ''}" data-id="${task.id}">
                <div class="task-time">${task.startTime || '全天'}</div>
                <div class="task-content">
                    <div class="task-title">${task.title}</div>
                    ${task.description ? `<div class="task-description">${task.description}</div>` : ''}
                </div>
                <div class="task-actions">
                    <button class="btn-complete" title="完成">
                        <i class="fas fa-check"></i>
                    </button>
                    <button class="btn-edit" title="编辑">
                        <i class="fas fa-edit"></i>
                    </button>
                    <button class="btn-delete" title="删除">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            </div>
        `;
    });

    html += '</div></div>';
    return html;
}

/**
 * 生成日程时间表
 */
function generateDaySchedule(dayTasks) {
    let html = '';
    const timeSlots = Array.from({ length: 24 }, (_, hour) => {
        const hourTasks = dayTasks.filter(task => {
            if (!task.startTime) return false;
            const taskHour = parseInt(task.startTime.split(':')[0]);
            return taskHour === hour;
        });

        return `
            <div class="hour-slot" data-hour="${hour}">
                ${hourTasks.map(task => `
                    <div class="task-item ${task.completed ? 'completed' : ''}" 
                         data-id="${task.id}" 
                         style="height: ${calculateTaskHeight(task)}px">
                        <div class="task-content">
                            <div class="task-title">${task.title}</div>
                            <div class="task-time">${task.startTime}${task.endTime ? ` - ${task.endTime}` : ''}</div>
                        </div>
                    </div>
                `).join('')}
            </div>
        `;
    });

    // 添加全天事件
    const allDayTasks = dayTasks.filter(task => !task.startTime);
    if (allDayTasks.length > 0) {
        html += `
            <div class="all-day-events">
                ${allDayTasks.map(task => `
                    <div class="task-item ${task.completed ? 'completed' : ''}" data-id="${task.id}">
                        <div class="task-content">
                            <div class="task-title">${task.title}</div>
                        </div>
                    </div>
                `).join('')}
            </div>
        `;
    }

    html += timeSlots.join('');
    return html;
}

/**
 * 计算任务显示高度
 */
function calculateTaskHeight(task) {
    if (!task.startTime || !task.endTime) return 60; // 默认高度

    const start = task.startTime.split(':').map(Number);
    const end = task.endTime.split(':').map(Number);
    const duration = (end[0] * 60 + end[1]) - (start[0] * 60 + start[1]);
    return Math.max(60, duration); // 最小高度60px
}

/**
 * 绑定日历事件
 */
function bindCalendarEvents() {
    // 视图切换按钮
    document.querySelectorAll('.view-btn').forEach(btn => {
        btn.addEventListener('click', () => {
            currentView = btn.dataset.view;
            updateCalendarView();
        });
    });

    // 导航按钮
    const prevBtn = document.querySelector('.nav-btn.prev');
    const nextBtn = document.querySelector('.nav-btn.next');
    const todayBtn = document.querySelector('.nav-btn.today');

    if (prevBtn) {
        prevBtn.addEventListener('click', () => {
            navigateCalendar('prev');
        });
    }

    if (nextBtn) {
        nextBtn.addEventListener('click', () => {
            navigateCalendar('next');
        });
    }

    if (todayBtn) {
        todayBtn.addEventListener('click', () => {
            currentDate = new Date();
            updateCalendarView();
        });
    }

    // 添加待办按钮
    const addTaskBtn = document.getElementById('calendar-add-task');
    if (addTaskBtn) {
        addTaskBtn.addEventListener('click', () => {
            showTaskModal();
        });
    }

    // 任务项点击事件
    document.querySelectorAll('.task-item').forEach(item => {
        item.addEventListener('click', (e) => {
            const taskId = item.dataset.id;
            const task = tasks.find(t => t.id === taskId);
            if (task) {
                if (e.target.closest('.btn-complete')) {
                    toggleTaskComplete(taskId);
                } else if (e.target.closest('.btn-edit')) {
                    showTaskModal(task);
                } else if (e.target.closest('.btn-delete')) {
                    if (confirm('确定要删除这个待办事项吗？')) {
                        deleteTask(taskId);
                    }
                } else {
                    showTaskDetails(task);
                }
            }
        });
    });

    // 日期格子点击事件（用于快速添加任务）
    document.querySelectorAll('.calendar-day').forEach(day => {
        day.addEventListener('dblclick', () => {
            const date = day.dataset.date;
            showTaskModal(null, date);
        });
    });
}

/**
 * 日历导航
 */
function navigateCalendar(direction) {
    switch (currentView) {
        case CalendarViewType.MONTH:
            currentDate.setMonth(currentDate.getMonth() + (direction === 'prev' ? -1 : 1));
            break;
        case CalendarViewType.WEEK:
            currentDate.setDate(currentDate.getDate() + (direction === 'prev' ? -7 : 7));
            break;
        case CalendarViewType.DAY:
            currentDate.setDate(currentDate.getDate() + (direction === 'prev' ? -1 : 1));
            break;
        case CalendarViewType.SCHEDULE:
            currentDate.setDate(currentDate.getDate() + (direction === 'prev' ? -30 : 30));
            break;
    }
    updateCalendarView();
}

/**
 * 显示任务详情
 */
function showTaskDetails(task) {
    const modal = document.createElement('div');
    modal.className = 'task-details-modal';
    modal.innerHTML = `
        <div class="task-details">
            <div class="task-details-header">
                <h3>${task.title}</h3>
                <button class="btn-close"><i class="fas fa-times"></i></button>
            </div>
            <div class="task-details-content">
                <div class="detail-item">
                    <label>日期：</label>
                    <span>${formatDateForDisplay(new Date(task.date))}</span>
                </div>
                ${task.startTime ? `
                    <div class="detail-item">
                        <label>时间：</label>
                        <span>${task.startTime}${task.endTime ? ` - ${task.endTime}` : ''}</span>
                    </div>
                ` : ''}
                ${task.description ? `
                    <div class="detail-item">
                        <label>描述：</label>
                        <p>${task.description}</p>
                    </div>
                ` : ''}
                <div class="detail-item">
                    <label>状态：</label>
                    <span>${task.completed ? '已完成' : '未完成'}</span>
                </div>
            </div>
            <div class="task-details-actions">
                <button class="btn-edit">编辑</button>
                <button class="btn-delete">删除</button>
            </div>
        </div>
    `;

    document.body.appendChild(modal);

    // 绑定事件
    modal.querySelector('.btn-close').addEventListener('click', () => {
        modal.remove();
    });

    modal.querySelector('.btn-edit').addEventListener('click', () => {
        modal.remove();
        showTaskModal(task);
    });

    modal.querySelector('.btn-delete').addEventListener('click', () => {
        if (confirm('确定要删除这个待办事项吗？')) {
            deleteTask(task.id);
            modal.remove();
        }
    });

    modal.addEventListener('click', (e) => {
        if (e.target === modal) {
            modal.remove();
        }
    });
}

/**
 * 格式化日期显示
 */
function formatDateForDisplay(date) {
    return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        weekday: 'long'
    });
}

// 导出模块
module.exports = {
    initialize,
    loadTasks,
    showTaskModal,
    hideTaskModal,
    saveTask,
    updateTasksDisplay,
    updateTaskCount,
    setupEventListeners
}; 